package com.maixy.esdemo.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.Arrays;

/**
 * @ClassName ESTestDocInsert
 * @Description TODO
 * @Date 2021/4/16 22:40
 * @Author maixy
 */
public class ESTestDocInsertBatch {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient esClient =new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200, "http")));

        //批量插入数据
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("1001")
                .source(XContentType.JSON, "name", "张三", "sex","男","age",29));
        request.add(new IndexRequest().index("user").id("1002")
                .source(XContentType.JSON, "name", "李四", "sex","女","age",19));
        request.add(new IndexRequest().index("user").id("1003")
                .source(XContentType.JSON, "name", "王五", "sex","男","age",59));
        request.add(new IndexRequest().index("user").id("1004")
                .source(XContentType.JSON, "name", "王五1", "sex","女","age",25));
        request.add(new IndexRequest().index("user").id("1005")
                .source(XContentType.JSON, "name", "王五2", "sex","男","age",10));

        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(Arrays.toString(response.getItems()));
        esClient.close();
    }
}
